import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { LoggerService } from '../logger/logger.service';
import { Inject } from '@nestjs/common';

@Injectable()
export class HttpLoggerMiddleware implements NestMiddleware {
  constructor(
    private readonly logger: LoggerService,
  ) {
    this.logger.setContext('HttpLoggerMiddleware');
  }

  use(req: Request, res: Response, next: NextFunction) {
    const { method, originalUrl, ip, headers } = req;
    const userAgent = headers['user-agent'] || '';
    const startTime = Date.now();

    // 请求开始日志
    this.logger.log(
      `Request - ${method} ${originalUrl} - IP: ${ip}`,
    );

    // 响应完成时记录日志
    res.on('finish', () => {
      const { statusCode } = res;
      const contentLength = res.get('content-length');
      const responseTime = Date.now() - startTime;

      // 根据状态码决定日志级别
      if (statusCode >= 500) {
        this.logger.error(
          `Response - ${method} ${originalUrl} - ${statusCode} - ${responseTime}ms - ${contentLength || 0}B`,
          undefined,
        );
      } else if (statusCode >= 400) {
        this.logger.warn(
          `Response - ${method} ${originalUrl} - ${statusCode} - ${responseTime}ms - ${contentLength || 0}B`,
        );
      } else {
        this.logger.log(
          {
            message: `Response - ${method} ${originalUrl}`,
            statusCode,
            responseTime: `${responseTime}ms`,
            contentLength: `${contentLength || 0}B`,
            userAgent,
          },
        );
      }
    });

    next();
  }
}
